/*
 * @Description: 表单验证
 * @Autor: lcz
 * @Date: 2022-08-17 09:35:32
 * @LastEditors: lcz
 * @LastEditTime: 2022-08-17 10:16:30
 */


interface regFormProps {
  [key: string]: any
}

interface regFormRuleProps {
  [key: string]: regFormRuleItemProps[] | regFormRuleItemProps
}

interface regFormRuleItemProps {
  require?: boolean
  errorMsg: string
  reg?: RegExp
}

/**
 * @description: 数组循环调用对象判断
 * @param {*} arr
 * @param {*} from
 * @param {*} el key
 * @return {*}
 */
function arrMap<T extends object>(arr: Array<any>, from: T, el: string): [null | string, boolean] {
  let returnInfo: [null | string, boolean] = [null, true]
  for (let i = 0, lenght = arr.length; i < lenght; i++) {
    let [error, status] = rzObject(arr[i], from, el)
    if (!status) {
      returnInfo = [error, status]
      break
    }
  }
  return returnInfo
}

/**
 * @description: 对象判断验证是否成功
 * @param {*} rzObj
 * @param {*} from
 * @param {*} el
 * @return {*}
 */

function rzObject(rzObj: regFormRuleItemProps, from: regFormProps, el: string): [null | string, boolean] {
  let value = from[el]
  if (rzObj.require && value.length <= 0) {
    return [rzObj.errorMsg, false]
  }
  if (rzObj.reg && !rzObj.reg.test(value) && value.length > 0) {
    return [rzObj.errorMsg, false]
  }
  return [null, true]
}

/**
 * @description: 表单规则验证
 * @param {*} from
 * @param {*} rule
 * @return {*}
 */


export function regFrom(from: regFormProps, rule: regFormRuleProps): [null | string, boolean] {
  const formArr: string[] = Object.keys(from)
  let info: [null | string, boolean] = [null, true]
  for (let i = 0, lenght = formArr.length; i < lenght; i++) {
    const item = rule[formArr[i]]
    if (Array.isArray(item)) {
      var [error, status] = arrMap(item, from, formArr[i])
    } else if (item.constructor === Object) {
      var [error, status] = rzObject(item, from, formArr[i])
    }
    if (!status) {
      info = [error, status]
      break
    }
  }
  return info
}
